#coding:utf-8
'''
author:Cooper
date:2012.5.8
'''

__all__=["getConn","request"]

config={
    'mysqld_win':{
    'host':'localhost',
    'user':'root',
    'pw':'',
    'charset':'utf8'
    },
    'mysqld_linux':{
    'host':'localhost',
    'user':'root',
    'pw':'LTS98',
    'charset':'utf8'
    }
}

import sys,os
import requests

sys_encoding=sys.getfilesystemencoding()
#platform=sys.platform
os_name=os.name

def getConn(db='test'):
	import MySQLdb
    conn=None
    try:
    	if os_name=='posix':
	        conn = MySQLdb.connect(host=config['mysqld_linux']['host']),
	                               user=config['mysqld_linux']['user']),
	                               passwd=config['mysqld_linux']['pw']),
	                               db=db,
	                               charset=config['mysqld_linux']['charset']))
	    elif os_name=='nt':
	    	conn = MySQLdb.connect(host=config['mysqld_win']['host']),
                                   user=config['mysqld_win']['user']),
                                   passwd=config['mysqld_win']['pw']),
                                   db=db,
                                   charset=config['mysqld_win']['charset']))
    except:
        conn=None
	return conn

def request(url,method='GET',retries=5):
	r=None
    while 1:
        try:
            r=requests.request(method,url,timeout=10)
            t=r.content
            break
        except:
            if retries>0:r=request(url,method,retries-1)
    return r

def mkDirX(path):
    '''Create directory,X edition.'''
    if os.path.exists(path):
        return
    path=path.replace('\\',r'/')
    try:
        os.mkdir(path)
    except:
        mkDirX(path.strip('/')[:path.strip('/').rindex('/')])
        mkDirX(path.strip('/'))
    pass

def copyX(src,dst,override,ignore=[]):
    '''Like Windows copyX,copy everything to another folder.'''
    if not os.path.isdir(src):
        sys.exit(0)
    if not os.path.exists(dst):
        mkDirX(dst)
    log=list()
    for o in os.listdir(src):
        if len(ignore)>0:
            r=r'({0})$'.format('\\'+'|\\'.join(ignore))
            if len(__import__('re').findall(r,o))>0:
                continue
        if os.path.isfile(src+'/'+o):
            if os.path.exists(dst+'/'+o) and override:
                os.remove(dst+'/'+o)
                shutil.copy(src+'/'+o,dst+'/'+o)
                log.append('updated:'+dst+'/'+o)
            else:
                shutil.copy(src+'/'+o,dst+'/'+o)
                log.append('added:'+dst+'/'+o)
        elif os.path.isdir(src+'/'+o):
            if not os.path.exists(dst+'/'+o):
                mkDirX(dst+'/'+o)
                log.append('added:'+dst+'/'+o)
            return log+copyX(src+'/'+o,dst+'/'+o,override,ignore)
    return log

def syncDir(src,dst,ignore=[]):
    '''synchronous files from path1 to path2,return a log list'''
    log=list()
    for o in os.listdir(src):
        if len(ignore)>0:
            r=r'({0})$'.format('\\'+'|\\'.join(ignore))
            if len(__import__('re').findall(r,o))>0:
                continue
        if os.path.isfile(src+'/'+o):
            if os.path.exists(dst+'/'+o):
                if os.path.getmtime(src+'/'+o)>os.path.getmtime(dst+'/'+o):
                    os.remove(dst+'/'+o)
                    shutil.copy(src+'/'+o,dst+'/'+o)
                    log.append('updated:'+dst+'/'+o)
            else:
                shutil.copy(src+'/'+o,dst+'/'+o)
                log.append('added:'+dst+'/'+o)
        elif os.path.isdir(src+'/'+o):
            if os.path.exists(dst+'/'+o):
                log+=syncDir(src+'/'+o,dst+'/'+o, ignore)
            else:
                copyX(src+'/'+o, dst+'/'+o, False ,ignore)
                log.append('added:'+dst+'/'+o)
    return log

def listFilesX(path):
    '''Return files from directory,subfolders included.'''
    l=list()
    for t in os.listdir(path):
        if os.path.isfile(path+'/'+t):
            l.append(path+'/'+t)
        elif os.path.isdir(path+'/'+t):
            l=l+listFilesX(path+'/'+t)
    return l

def mysql_db_export(db,path=os.getcwd()):
    import xlwt
    wb=xlwt.Workbook('utf-8')
    conn=getConn(db)
    if not conn:sys.exit('MySQL Connection Error')
    conn.query('show tables')
    r=conn.store_result()
    del xlwt

def main():
	pass

if __name__ == '__main__':
	main()